diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py
index fbd55606ae..38312c1bc0 100644
--- a/django/contrib/contenttypes/fields.py
+++ b/django/contrib/contenttypes/fields.py
@@ -199,13 +199,13 @@ class GenericForeignKey(FieldCacheMixin):
         # content type, so we use a callable that returns a (fk, class) pair.
         def gfk_key(obj):
             ct_id = getattr(obj, ct_attname)
-            if ct_id is None:
-                return None
+            fk_val = getattr(obj, self.fk_field)
+            if ct_id is None or fk_val is None:
+                # If the content type or foreign key value is None, return them as is
+                return (fk_val, ct_id)
             else:
-                model = self.get_content_type(id=ct_id,
-                                              using=obj._state.db).model_class()
-                return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),
-                        model)
+                model = self.get_content_type(id=ct_id, using=obj._state.db).model_class()
+                return (model._meta.pk.get_prep_value(fk_val), model)
 
         return (
             ret_val,
